package com.auto.survey.activity.monitoring.dao

import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.Query
import androidx.room.Transaction
import androidx.room.Update
import com.auto.survey.activity.monitoring.entity.ctrlmeasure.ClosedLoopObservation
import com.auto.survey.activity.monitoring.entity.ctrlmeasure.ClosedLoopWithPoints

@Dao
interface ClosedLoopObservationDao {
    /**
     * 插入单个闭合观测序列
     */
    @Insert
    suspend fun insert(loop: ClosedLoopObservation): Long

    /**
     * 批量插入闭合观测序列
     */
    @Insert
    suspend fun insertAll(loops: List<ClosedLoopObservation>): List<Long>

    /**
     * 查询所有闭合观测序列（含关联的观测点和监测点）
     */
    @Transaction
    @Query("SELECT * FROM ClosedLoopObservation ORDER BY createTime DESC")
    suspend fun getAllClosedLoopsWithPoints(): List<ClosedLoopWithPoints>

    /**
     * 根据ID查询单个闭合观测序列（含关联数据）
     */
    @Transaction
    @Query("SELECT * FROM ClosedLoopObservation WHERE id = :loopId")
    suspend fun getClosedLoopWithPointsById(loopId: Int): ClosedLoopWithPoints?

    /**
     * 根据站点ID查询该站点下的所有闭合序列（用于StationWithClosedLoop）
     */
    @Query("SELECT * FROM ClosedLoopObservation WHERE stationId = :stationId")
    suspend fun getLoopsByStationId(stationId: Int): List<ClosedLoopObservation>

    /**
     * 更新闭合序列的状态和完成时间
     */
    @Query("UPDATE ClosedLoopObservation SET status = :status, completeTime = :completeTime WHERE id = :loopId")
    suspend fun updateStatusAndTime(loopId: Int, status: Int, completeTime: String): Int

    /**
     * 根据ID删除闭合序列（会触发中间表LoopObservationPoint的级联删除）
     */
    @Delete
    suspend fun delete(loop: ClosedLoopObservation): Int

    @Update
    suspend fun update(loop: ClosedLoopObservation)

    /**
     * 根据监测对象ID查询闭合序列
     */
    @Query("SELECT * FROM ClosedLoopObservation WHERE monitoringObjectId = :objectId")
    suspend fun getLoopsByObjectId(objectId: Int): List<ClosedLoopObservation>
}